package com.cwits.wifi.ui.activity;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cwits.wifi.R;
import com.cwits.wifi.base.BaseActivity;
import com.cwits.wifi.util.PreferencesHelper;

import java.util.Locale;
import java.util.Random;

/**
 * Created by ZhangHua on 16-03-01.
 */
public class MyInfoActivity extends BaseActivity implements View.OnClickListener {
    private RelativeLayout mBack;
    private WebView mWebView;
    private boolean mIsNeedReConnect = true;
    private boolean mLoad = true;
    private ProgressDialog progressDialog;

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                ConnectivityManager mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo netInfo = mConnectivityManager.getActiveNetworkInfo();
                if (netInfo != null && netInfo.isAvailable()) {

                    /////////////网络连接
                    mWebView.reload();
                } else {
                    ////////网络断开

                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.myinfolayout);
        mBack = (RelativeLayout) findViewById(R.id.left_imageview);
        mWebView = (WebView) findViewById(R.id.webView);
        if (getIntent().hasExtra("title")) {
            ((TextView) findViewById(R.id.titile_back)).setText(getIntent().getStringExtra("title"));
        }
        if (mApplication.getIsOffLineMode() == false) {
            disconnectDevice();
            mApplication.setIsOffLineMode(true);
            mApplication.setRealCamera(false);
            mApplication.setIsNeedReconnect(true);
        }

        mWebView.setWebViewClient(mWebViewClient);
        mWebView.setVisibility(View.INVISIBLE);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setAppCacheEnabled(false);
        Locale locale = getResources().getConfiguration().locale;
        String language = locale.getLanguage();
        if (language.endsWith("zh")) {
            if (!getIntent().hasExtra("url")) {
                mWebView.loadUrl("http://cross.kcnzq.net:8099/app/news.html?random=" + new Random().nextInt(99999999));
            } else {
                mWebView.loadUrl(getIntent().getStringExtra("url"));
            }
        } else {
            if (!getIntent().hasExtra("url")) {
                mWebView.loadUrl("http://cross.kcnzq.net:8099/app/newse.html?random=" + new Random().nextInt(99999999));
            } else {
                mWebView.loadUrl(getIntent().getStringExtra("url"));
            }
        }
        mWebView.setWebChromeClient(new WebChromeClient() {
                                        public void onProgressChanged(WebView view, int progress) {
                                        }
                                    }
        );
        mBack.setOnClickListener(this);
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(mReceiver, filter);

        //lihaoran: clear PushMSM count
        clearPushMSMCount();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.left_imageview:
                if (mWebView.canGoBack()) {
                    mWebView.goBack();
                } else {
                    finish();
                }

                break;
        }
    }

    @Override
    public void onBackPressed() {
        if (mWebView.canGoBack()) {
            mWebView.goBack();
        } else {
            finish();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        this.unregisterReceiver(mReceiver);
    }

    private void clearPushMSMCount() {
        int msmCount = PreferencesHelper.getSharedPreferences(this).getInt("PushMSMCount", 0);
        if (msmCount != 0) {
            PreferencesHelper.putIntValue(this, "PushMSMCount", 0);
        }
    }

    private final WebViewClient mWebViewClient = new WebViewClient() {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, android.net.http.SslError error) {
            handler.proceed();
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            // TODO Auto-generated method stub
            super.onReceivedError(view, errorCode, description, failingUrl);
            mLoad = false;
            switch (errorCode) {
                case WebViewClient.ERROR_TIMEOUT:
                case WebViewClient.ERROR_CONNECT:
                case WebViewClient.ERROR_HOST_LOOKUP:
                    if (progressDialog != null && progressDialog.isShowing()) {
                        progressDialog.dismiss();
                    }

                    break;
            }
            mWebView.setVisibility(View.INVISIBLE);
        }

        //在页面加载开始时调用。
        @Override
        public void onPageFinished(WebView view, String url) {
            // TODO Auto-generated method stub
            super.onPageFinished(view, url);
            if (progressDialog != null && progressDialog.isShowing()) {
                progressDialog.dismiss();
            }
            if (mLoad)
                mWebView.setVisibility(View.VISIBLE);
        }

        //在加载页面资源时会调用，每一个资源（比如图片）的加载都会调用一次。
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            // TODO Auto-generated method stub
            super.onPageStarted(view, url, favicon);
            mLoad = true;
            if (progressDialog == null) {
                progressDialog = new ProgressDialog(MyInfoActivity.this);
                progressDialog.setMessage(getString(R.string.data_downloading));
            }
            progressDialog.show();
        }

        //重写此方法才能够处理在浏览器中的按键事件
        @Override
        public void onLoadResource(WebView view, String url) {
            // TODO Auto-generated method stub
            super.onLoadResource(view, url);

        }

        //重写此方法可以让webview处理https请求。
        @Override
        public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
            return super.shouldOverrideKeyEvent(view, event);
        }

    };
}
